package com.suse.service.community.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.suse.common.base.model.entity.Page;
import com.suse.service.community.entity.DiscussPost;
import com.suse.service.community.repository.DiscussPostRepository;
import com.suse.service.community.service.ElasticsearchService;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * Elasticsearch业务实现类
 * </p>
 *
 * @author 辜玉彬
 * @since 2022-09-04 14:40
 */
@Service
public class ElasticsearchServiceImpl implements ElasticsearchService {

    @Resource
    private DiscussPostRepository discussPostRepository;

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public void saveDiscussPost(DiscussPost post) {
        discussPostRepository.save(post);
    }

    @Override
    public void removeDiscussPost(int id) {
        discussPostRepository.deleteById(id);
    }

    @Override
    public List<DiscussPost> searchDiscussPost(String keyword, Page page) {
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.multiMatchQuery(keyword, "title", "content"))
                .withSort(SortBuilders.fieldSort("type").order(SortOrder.DESC))
                .withSort(SortBuilders.fieldSort("score").order(SortOrder.DESC))
                // .withSort(SortBuilders.fieldSort("createTime").order(SortOrder.DESC))
                .withPageable(PageRequest.of(page.getCurrent() - 1, page.getLimit()))
                .withHighlightFields(
                        new HighlightBuilder.Field("title").postTags("<em>").postTags("</em>"),
                        new HighlightBuilder.Field("content").postTags("<em>").postTags("</em>")
                ).build();
        SearchHits<DiscussPost> searchHits = elasticsearchRestTemplate.search(searchQuery, DiscussPost.class);
        // 分页信息
        page.setTotal(searchHits.getTotalHits());
        // 分页列表
        List<DiscussPost> discussPostList = new ArrayList<>();
        searchHits.get().forEach((searchHit) -> {
            DiscussPost discussPost = searchHit.getContent();
            List<String> wordList = searchHit.getHighlightField("title");
            if (CollectionUtil.isNotEmpty(wordList)) {
                StringBuilder builder = new StringBuilder();
                for (String word : wordList) {
                    builder.append(word);
                }
                discussPost.setTitle(builder.toString());
            }
            wordList = searchHit.getHighlightField("content");
            if (CollectionUtil.isNotEmpty(wordList)) {
                StringBuilder builder = new StringBuilder();
                for (String word : wordList) {
                    builder.append(word);
                }
                discussPost.setContent(builder.toString());
            }

            discussPostList.add(discussPost);
        });
        return discussPostList;
    }

}
